package com.example.gridview;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;


public class CommentsManager {

  // Database fields
  private SQLiteDatabase database;
  private DbHelper dbHelper;
  private String[] allColumns = {
		  DbHelper.COLUMN_ID,
		  DbHelper.COLUMN_TITLE,
		  DbHelper.COLUMN_COMMENT };

  public CommentsManager(Context context) {
    dbHelper = new DbHelper(context);
  }

  public void open() throws SQLException {
    database = dbHelper.getWritableDatabase();
  }

  public void close() {
    dbHelper.close();
  }

  public Comment createComment(String title, String comment) {
    ContentValues values = new ContentValues();
    values.put(DbHelper.COLUMN_TITLE, title);
    values.put(DbHelper.COLUMN_COMMENT, comment);
    long insertId = database.insert(DbHelper.TABLE_COMMENTS, null,
        values);
    Cursor cursor = database.query(DbHelper.TABLE_COMMENTS,
        allColumns, DbHelper.COLUMN_ID + " = " + insertId, null,
        null, null, null);
    cursor.moveToFirst();
    Comment newComment = cursorToComment(cursor);
    cursor.close();
    return newComment;
  }

  public void deleteComment(Comment comment) {
    long id = comment.getId();
    System.out.println("Comment deleted with id: " + id);
    database.delete(DbHelper.TABLE_COMMENTS, DbHelper.COLUMN_ID
        + " = " + id, null);
  }

  public int countRecords(){
	  int numOfRecords = 0;
	  Cursor cursor = database.query(DbHelper.TABLE_COMMENTS,
		        allColumns, null, null, null, null, null);
	  numOfRecords = cursor.getCount();
	  cursor.close();
	  
	return numOfRecords;
 }
  
  
  public List<Comment> getAllComments() {
    List<Comment> comments = new ArrayList<Comment>();

    Cursor cursor = database.query(DbHelper.TABLE_COMMENTS,
        allColumns, null, null, null, null, null);

    cursor.moveToFirst();
    while (!cursor.isAfterLast()) {
      Comment comment = cursorToComment(cursor);
      comments.add(comment);
      cursor.moveToNext();
    }
    // make sure to close the cursor
    cursor.close();
    return comments;
  }

  private Comment cursorToComment(Cursor cursor) {
    Comment comment = new Comment();
    comment.setId(cursor.getLong(0));
    comment.setTitle(cursor.getString(1));
    comment.setComment(cursor.getString(2));
    return comment;
  }
} 